<?php


namespace app\system\controller;

class Swoole extends AdminBase
{
	public function get_port_server_run_status()
	{
		$tcp_path = \think\facade\Env::get("root_path") . "runtime/ShuanQTcpService.log";
		$udp_path = \think\facade\Env::get("root_path") . "runtime/ShuanQUdpService.log";
		if (!is_file($tcp_path)) {
			$tcp_data = ["runtime" => 0, "pid" => 0];
		} else {
			$tcp_data = json_decode(file_get_contents($tcp_path));
		}
		if (!is_file($udp_path)) {
			$udp_data = ["runtime" => 0, "pid" => 0];
		} else {
			$udp_data = json_decode(file_get_contents($udp_path));
		}
		$data = ["tcp" => $tcp_data, "udp" => $udp_data];
		$this->response(\app\system\model\Code::success, "获取成功", $data);
	}
	public function refresh_port_server_run_status($type = "tcp")
	{
		if (!class_exists("swoole_server")) {
			$this->response(\app\system\model\Code::fail, "请先安装PHP扩展【swoole】");
		}
		list($ip, $port, $client) = open_swoole_client($type);
		if ($client || $type == "udp") {
			if ($type == "tcp") {
				$client->send("TestLog");
				$client->close();
				$this->response(\app\system\model\Code::success, "已刷新");
			} else {
				$client->sendto($ip, $port, json_encode(["mode" => "TestLog"]));
				$this->response(\app\system\model\Code::success, "已发送请求刷新(请确保udp服务端口正在运行否则无效)");
			}
		} else {
			$this->response(\app\system\model\Code::fail, "刷新失败，连接端口失败");
		}
	}
	public function close_port_server($type = "tcp")
	{
		if (!class_exists("swoole_server")) {
			$this->response(\app\system\model\Code::fail, "请先安装PHP扩展【swoole】");
		}
		list($ip, $port, $client) = open_swoole_client($type);
		if ($client || $type == "udp") {
			if ($type == "tcp") {
				$client->send("KillService");
				$client->close();
			} else {
				$client->sendto($ip, $port, json_encode(["mode" => "TestLog"]));
			}
			$this->response(\app\system\model\Code::success, "已发送关闭服务命令(具体以实际结果为准)");
		} else {
			$this->response(\app\system\model\Code::fail, "连接端口失败");
		}
	}
}